import time
import logging
import os
import numpy as np
from typing import Dict, Optional, List, Any, Callable, Tuple
from threading import Lock

# 确保导入cv2
try:
    import cv2
    cv2_available = True
except ImportError:
    cv2_available = False
    logging.warning("OpenCV未安装，场景分析功能将受限")

class SceneManager:
    """
    场景管理器类，负责管理不同的检测场景并在它们之间进行切换
    支持的场景类型：
    - traffic: 交通监控场景（默认）
    - helmet: 头盔检测场景
    - face: 人脸检测场景
    - all: 全场景模式，同时执行所有检测
    """
    
    def __init__(self, custom_config: Optional[Dict[str, Any]] = None):
        """
        初始化场景管理器
        
        Args:
            custom_config: 自定义配置字典，可覆盖默认配置
        """
        self.logger = logging.getLogger(__name__)
        self._lock = Lock()  # 添加线程锁以确保线程安全
        
        # 场景类型定义 - 增强版配置
        self.SUPPORTED_SCENES = {
            'traffic': {
                'description': '交通监控场景', 
                'active': True,
                'priority': 3,
                'target_classes': [0, 1, 2, 3, 5, 7]  # person, bicycle, car, motorbike, bus, truck
            },
            'helmet': {
                'description': '头盔检测场景', 
                'active': True,
                'priority': 4,
                'target_classes': [0, 3],  # person, motorbike
                'helmet_classes': ['helmet', 'no_helmet']  # 头盔检测专用类别
            },
            'face': {
                'description': '人脸检测场景', 
                'active': True,
                'priority': 2,
                'target_classes': None  # 专用人脸检测使用
            },
            'all': {
                'description': '全场景模式', 
                'active': True,
                'priority': 5,
                'target_classes': None  # 检测所有类别
            }
        }
        
        # 当前场景
        self.current_scene = 'traffic'  # 默认场景为交通监控
        
        # 场景切换历史
        self.scene_history = []
        
        # 场景激活时间记录
        self.scene_activation_time = {
            scene: 0 for scene in self.SUPPORTED_SCENES.keys()
        }
        
        # 场景计数器（用于统计各场景使用频率）
        self.scene_counter = {
            scene: 0 for scene in self.SUPPORTED_SCENES.keys()
        }
        
        # 场景优先级配置（兼容旧配置）
        self.scene_priority = {
            'traffic': 3,
            'helmet': 4,
            'face': 2,
            'all': 5
        }
        
        # 场景识别配置
        self.scene_recognition_config = {
            'enable_auto_switch': True,      # 是否启用自动场景切换
            'min_switch_interval': 5.0,      # 最小场景切换间隔（秒）
            'confidence_threshold': 0.7,     # 场景识别置信度阈值
            'motion_detection_threshold': 10.0,  # 运动检测阈值
            'min_frame_size': 256,           # 最小处理帧尺寸
            'max_frame_size': 1024,          # 最大处理帧尺寸
        }
        
        # 检测引擎映射（延迟初始化，由主应用注入）
        self.detection_engines = {}
        
        # 场景特定配置 - 增强版，针对每个场景优化
        self.scene_specific_config = {
            'traffic': {
                'detection_interval': 1,     # 检测间隔（帧）
                'conf_threshold': 0.3,       # 检测置信度阈值
                'nms_threshold': 0.45,       # 非极大值抑制阈值
                'min_detection_size': 20,    # 最小检测目标尺寸
                'max_detection_size': None,  # 最大检测目标尺寸
                'analysis_features': {
                    'speed_estimation': True,
                    'flow_direction': True,
                    'queue_detection': True,
                    'congestion_analysis': True
                }
            },
            'helmet': {
                'detection_interval': 1,     # 检测间隔（帧）
                'conf_threshold': 0.3,       # 检测置信度阈值
                'nms_threshold': 0.45,       # 非极大值抑制阈值
                'min_detection_size': 10,    # 最小检测目标尺寸（头盔检测需要更小）
                'max_detection_size': None,
                'helmet_conf_threshold': 0.6, # 头盔检测专用置信度阈值
                'rider_conf_threshold': 0.5,  # 骑行者检测置信度阈值
                'analysis_features': {
                    'rider_detection': True,
                    'helmet_classification': True,
                    'non_helmet_alert': True,
                    'helmet_color_analysis': False  # 可选的头盔颜色分析
                }
            },
            'face': {
                'detection_interval': 1,     # 检测间隔（帧）
                'conf_threshold': 0.5,       # 检测置信度阈值
                'nms_threshold': 0.4,        # 非极大值抑制阈值
                'min_detection_size': 30,    # 人脸最小检测尺寸
                'max_detection_size': 300,   # 人脸最大检测尺寸
                'analysis_features': {
                    'face_recognition': False,
                    'emotion_detection': False,
                    'age_gender_estimation': False
                }
            },
            'all': {
                'detection_interval': 1,     # 检测间隔（帧）
                'conf_threshold': 0.3,       # 检测置信度阈值
                'nms_threshold': 0.45,       # 非极大值抑制阈值
                'min_detection_size': 10,    # 最小检测目标尺寸
                'max_detection_size': None,
                'analysis_features': {
                    'comprehensive_analysis': True,
                    'cross_scene_correlation': True
                }
            }
        }
        
        # 场景模型路径管理
        self.scene_model_paths = {
            'traffic': None,
            'helmet': None, 
            'face': None,
            'all': None
        }
        
        # 上次场景切换时间
        self.last_switch_time = time.time()
        
        # 场景特征缓存
        self.scene_features_cache = {}
        
        # 性能统计
        self.performance_stats = {
            'traffic': {'avg_processing_time': 0.0, 'frame_count': 0, 'fps': 0.0},
            'helmet': {'avg_processing_time': 0.0, 'frame_count': 0, 'fps': 0.0},
            'face': {'avg_processing_time': 0.0, 'frame_count': 0, 'fps': 0.0},
            'all': {'avg_processing_time': 0.0, 'frame_count': 0, 'fps': 0.0}
        }
        
        # 场景切换回调函数
        self.scene_switch_callbacks = []
        
        # 应用自定义配置
        if custom_config:
            self._apply_custom_config(custom_config)
        
        self.logger.info(f"场景管理器初始化完成，默认场景: {self.current_scene}")
        self.logger.info(f"支持的场景: {', '.join(self.SUPPORTED_SCENES.keys())}")
    
    def _apply_custom_config(self, config: Dict[str, Any]):
        """
        应用自定义配置
        
        Args:
            config: 自定义配置字典
        """
        # 应用场景特定配置
        if 'scene_configs' in config:
            for scene, scene_config in config['scene_configs'].items():
                if scene in self.scene_specific_config:
                    self.scene_specific_config[scene].update(scene_config)
                    self.logger.info(f"应用自定义配置到场景 '{scene}'")
        
        # 应用模型路径配置
        if 'model_paths' in config:
            for scene, model_path in config['model_paths'].items():
                if scene in self.scene_model_paths and os.path.exists(model_path):
                    self.scene_model_paths[scene] = model_path
                    self.logger.info(f"为场景 '{scene}' 设置模型路径: {model_path}")
                else:
                    self.logger.warning(f"无效的模型路径配置: {scene} -> {model_path}")
        
        # 应用场景识别配置
        if 'recognition_config' in config:
            self.scene_recognition_config.update(config['recognition_config'])
            self.logger.info(f"更新场景识别配置")
    
    def register_detection_engine(self, scene_type: str, engine: Any, 
                                 model_path: Optional[str] = None, 
                                 engine_config: Optional[Dict[str, Any]] = None):
        """
        注册检测引擎
        
        Args:
            scene_type: 场景类型
            engine: 检测引擎实例
            model_path: 模型路径（可选）
            engine_config: 引擎配置参数（可选）
        """
        with self._lock:
            if scene_type in self.SUPPORTED_SCENES:
                self.detection_engines[scene_type] = engine
                
                # 注册模型路径
                if model_path:
                    self.scene_model_paths[scene_type] = model_path
                    self.logger.info(f"为场景 '{scene_type}' 设置模型路径: {model_path}")
                
                # 应用引擎特定配置
                if engine_config and scene_type in self.scene_specific_config:
                    self.scene_specific_config[scene_type].update(engine_config)
                    self.logger.info(f"更新场景 '{scene_type}' 的引擎配置")
                
                self.logger.info(f"为场景 '{scene_type}' 注册检测引擎")
            else:
                self.logger.warning(f"不支持的场景类型: {scene_type}")
    
    def get_detection_engine(self, scene_type: Optional[str] = None) -> Optional[Any]:
        """
        获取指定场景的检测引擎
        
        Args:
            scene_type: 场景类型，默认获取当前场景的引擎
            
        Returns:
            检测引擎实例，如果不存在则返回None
        """
        with self._lock:
            target_scene = scene_type or self.current_scene
            if target_scene in self.detection_engines:
                return self.detection_engines[target_scene]
            self.logger.warning(f"场景 '{target_scene}' 未注册检测引擎")
            return None
    
    def switch_scene(self, scene_type: str, camera_id: Optional[str] = None, force: bool = False) -> bool:
        """
        切换检测场景
        
        Args:
            scene_type: 目标场景类型
            camera_id: 摄像头ID（可选）
            force: 是否强制切换（忽略时间间隔限制）
            
        Returns:
            是否成功切换场景
        """
        with self._lock:
            # 检查是否为支持的场景
            if scene_type not in self.SUPPORTED_SCENES:
                self.logger.error(f"不支持的场景类型: {scene_type}")
                return False
            
            # 检查场景是否激活
            if not self.SUPPORTED_SCENES[scene_type]['active']:
                self.logger.error(f"场景 '{scene_type}' 未激活")
                return False
            
            # 如果已经是当前场景，不需要切换
            if scene_type == self.current_scene:
                self.logger.debug(f"已经在场景 '{scene_type}' 中")
                return True
            
            # 检查场景切换间隔
            current_time = time.time()
            if not force and current_time - self.last_switch_time < self.scene_recognition_config['min_switch_interval']:
                self.logger.warning(f"场景切换过于频繁，距离上次切换仅 {current_time - self.last_switch_time:.2f} 秒")
                return False
            
            # 更新当前场景
            old_scene = self.current_scene
            self.current_scene = scene_type
            
            # 更新激活时间
            self.scene_activation_time[scene_type] = current_time
            
            # 增加场景计数
            self.scene_counter[scene_type] += 1
            
            # 更新上次切换时间
            self.last_switch_time = current_time
            
            # 记录场景切换历史
            self.scene_history.append({
                'timestamp': current_time,
                'from_scene': old_scene,
                'to_scene': scene_type,
                'camera_id': camera_id,
                'reason': 'force' if force else 'manual_switch'
            })
            
            # 限制历史记录长度
            if len(self.scene_history) > 1000:
                self.scene_history.pop(0)
            
            # 重置性能统计
            self.performance_stats[scene_type]['frame_count'] = 0
            self.performance_stats[scene_type]['avg_processing_time'] = 0.0
            self.performance_stats[scene_type]['fps'] = 0.0
            
            self.logger.info(f"场景从 '{old_scene}' 切换到 '{scene_type}'，摄像头ID: {camera_id} (原因: {'force' if force else 'manual_switch'})")
            
            # 触发场景切换事件
            self._on_scene_switch(old_scene, scene_type, camera_id)
            
            return True
    
    def get_active_engine(self) -> Optional[Any]:
        """
        获取当前激活的检测引擎
        
        Returns:
            当前场景对应的检测引擎，如果未注册则返回None
        """
        # 对于'all'场景，我们返回None，因为主应用需要协调多个引擎
        if self.current_scene == 'all':
            return None
        
        engine = self.detection_engines.get(self.current_scene)
        if engine is None:
            self.logger.warning(f"场景 '{self.current_scene}' 的检测引擎未注册")
        
        return engine
    
    def get_all_engines(self) -> Dict[str, Any]:
        """
        获取所有已注册的检测引擎
        
        Returns:
            检测引擎字典
        """
        return self.detection_engines.copy()
    
    def get_scene_config(self, scene_type: Optional[str] = None) -> Dict[str, Any]:
        """
        获取特定场景的配置
        
        Args:
            scene_type: 场景类型，如果为None则获取当前场景的配置
            
        Returns:
            场景配置字典
        """
        if scene_type is None:
            scene_type = self.current_scene
        
        if scene_type in self.scene_specific_config:
            return self.scene_specific_config[scene_type].copy()
        else:
            self.logger.warning(f"场景 '{scene_type}' 的配置不存在，返回默认配置")
            return self.scene_specific_config['traffic'].copy()
    
    def update_scene_config(self, scene_type: str, config_updates: Dict[str, Any]):
        """
        更新场景配置
        
        Args:
            scene_type: 场景类型
            config_updates: 要更新的配置项
        """
        if scene_type in self.scene_specific_config:
            self.scene_specific_config[scene_type].update(config_updates)
            self.logger.info(f"更新场景 '{scene_type}' 的配置: {config_updates}")
        else:
            self.logger.warning(f"场景 '{scene_type}' 不存在，无法更新配置")
    
    def register_scene_switch_callback(self, callback: Callable[[str, str, Optional[str]], None]) -> bool:
        """
        注册场景切换回调函数
        
        Args:
            callback: 回调函数，接收旧场景、新场景和摄像头ID作为参数
            
        Returns:
            bool: 是否注册成功
        """
        if not callable(callback):
            self.logger.error(f"回调必须是可调用的函数")
            return False
        
        with self._lock:
            if callback not in self.scene_switch_callbacks:
                self.scene_switch_callbacks.append(callback)
                self.logger.info(f"场景切换回调函数注册成功")
                return True
            else:
                self.logger.warning(f"回调函数已存在")
                return False
    
    def auto_switch_scene(self, frame: np.ndarray, 
                         detection_results: Optional[List[Dict[str, Any]]] = None,
                         camera_id: Optional[str] = None) -> bool:
        """
        根据画面内容和检测结果自动切换场景
        
        Args:
            frame: 当前视频帧
            detection_results: 可选的检测结果，用于更精确的场景分析
            camera_id: 摄像头ID
            
        Returns:
            是否成功切换场景
        """
        # 检查是否启用自动切换
        if not self.scene_recognition_config['enable_auto_switch']:
            return False
        
        try:
            # 分析画面内容和检测结果，确定最合适的场景
            scene_analysis = self._analyze_scene_content(frame, detection_results)
            
            # 根据分析结果选择场景
            target_scene = self._select_optimal_scene(scene_analysis)
            
            # 如果目标场景与当前场景不同，则切换场景
            if target_scene != self.current_scene:
                self.logger.info(f"自动切换场景: {self.current_scene} -> {target_scene}")
                result = self.switch_scene(target_scene, camera_id)
                if result:
                    # 更新场景切换历史中的原因
                    if self.scene_history:
                        self.scene_history[-1]['reason'] = 'auto_switch'
                        self.scene_history[-1]['analysis'] = scene_analysis
                return result
            
            return False
            
        except Exception as e:
            self.logger.error(f"自动场景切换失败: {str(e)}")
            return False
    
    def update_performance_stats(self, scene_type: str, processing_time: float, fps: Optional[float] = None):
        """
        更新场景性能统计
        
        Args:
            scene_type: 场景类型
            processing_time: 处理时间（毫秒）
            fps: 帧率（可选）
        """
        with self._lock:
            if scene_type in self.performance_stats:
                # 使用移动平均更新处理时间
                stats = self.performance_stats[scene_type]
                stats['frame_count'] += 1
                alpha = 0.1  # 平滑因子
                stats['avg_processing_time'] = stats['avg_processing_time'] * (1 - alpha) + processing_time * alpha
                
                # 更新FPS
                if fps is not None:
                    stats['fps'] = stats['fps'] * (1 - alpha) + fps * alpha
    
    def get_performance_stats(self, scene_type: Optional[str] = None) -> Dict[str, Any]:
        """
        获取场景性能统计
        
        Args:
            scene_type: 场景类型，默认获取所有场景统计
            
        Returns:
            性能统计字典
        """
        with self._lock:
            if scene_type:
                return self.performance_stats.get(scene_type, {})
            return self.performance_stats.copy()
    
    def _analyze_scene_content(self, frame: np.ndarray, 
                             detection_results: Optional[List[Dict[str, Any]]] = None) -> Dict[str, float]:
        """
        分析画面内容和检测结果，提取场景特征
        
        Args:
            frame: 输入视频帧
            detection_results: 可选的检测结果
            
        Returns:
            场景分析结果，包含各场景的置信度
        """
        # 初始化场景置信度
        scene_confidence = {
            'traffic': 0.0,
            'helmet': 0.0,
            'face': 0.0,
            'all': 0.0
        }
        
        # 1. 基于检测结果的场景分析（如果有）
        if detection_results and len(detection_results) > 0:
            self._analyze_scene_by_detections(detection_results, scene_confidence)
        
        # 2. 基于图像特征的场景分析（补充）
        self._analyze_scene_by_image_features(frame, scene_confidence)
        
        # 3. 考虑场景使用历史和上下文因素
        self._analyze_scene_by_context(scene_confidence)
        
        return scene_confidence
    
    def _analyze_scene_by_detections(self, detection_results: List[Dict[str, Any]], 
                                    scene_confidence: Dict[str, float]):
        """
        基于检测结果分析场景
        
        Args:
            detection_results: 检测结果列表
            scene_confidence: 场景置信度字典（将被更新）
        """
        # 统计各类别出现次数
        class_counts = {}
        helmet_counts = {'helmet': 0, 'no_helmet': 0}
        detection_count = len(detection_results)
        
        for result in detection_results:
            cls = result.get('class')
            if isinstance(cls, int):
                class_counts[cls] = class_counts.get(cls, 0) + 1
            
            # 检查是否有头盔检测标记
            if 'helmet_status' in result:
                helmet_status = result['helmet_status']
                if helmet_status in helmet_counts:
                    helmet_counts[helmet_status] += 1
        
        # 交通场景分析
        traffic_classes = self.SUPPORTED_SCENES['traffic'].get('target_classes', [0, 1, 2, 3, 5, 7])
        traffic_count = sum(class_counts.get(cls, 0) for cls in traffic_classes)
        
        if traffic_count > 0:
            # 交通场景置信度基于交通相关类别的比例
            traffic_ratio = traffic_count / detection_count
            scene_confidence['traffic'] = min(traffic_ratio * 1.2, 0.9)
        
        # 头盔场景分析（重点增强）
        helmet_related_count = 0
        has_motorbike = 3 in class_counts  # 3=摩托车类别
        has_person = 0 in class_counts    # 0=人类别
        
        # 统计头盔相关目标数量
        if has_motorbike:
            helmet_related_count += class_counts[3]
        if has_person:
            helmet_related_count += class_counts[0]
        
        # 核心头盔场景识别逻辑
        helmet_score = 0.0
        
        # 1. 如果同时检测到摩托车和人，这是头盔场景的强信号
        if has_motorbike and has_person:
            helmet_score += 0.6  # 基础分数
            
            # 2. 如果有头盔检测结果（helmet_status标记），进一步提高置信度
            helmet_detection_count = sum(helmet_counts.values())
            if helmet_detection_count > 0:
                helmet_score += 0.3  # 额外加分
            
            # 3. 根据摩托车和人的比例调整分数
            if has_motorbike and has_person:
                motorbike_count = class_counts[3]
                person_count = class_counts[0]
                # 理想情况：摩托车和人数量相近（1:1或1:2）
                ratio_score = min(motorbike_count / max(1, person_count), 
                                person_count / max(1, motorbike_count))
                helmet_score += ratio_score * 0.1
        
        # 4. 如果只有摩托车或人，给予基础分数
        elif helmet_related_count > 0:
            helmet_score += 0.3
        
        scene_confidence['helmet'] = min(helmet_score, 0.95)
        
        # 人脸场景分析
        # 人脸检测通常目标数量较少且置信度较高
        high_confidence_detections = sum(1 for r in detection_results 
                                       if r.get('confidence', 0) > 0.7)
        
        if high_confidence_detections > 0 and detection_count < 10:
            scene_confidence['face'] = min(high_confidence_detections / detection_count * 1.5, 0.9)
        
        # 全场景模式（当检测结果多样或无法明确分类时）
        if len(class_counts) >= 6 or detection_count > 20:
            scene_confidence['all'] = 0.7
        
        self.logger.debug(f"基于检测结果的场景分析: {scene_confidence}")
    
    def _analyze_scene_by_image_features(self, frame: np.ndarray, 
                                        scene_confidence: Dict[str, float]):
        """
        基于图像特征分析场景
        
        Args:
            frame: 输入帧
            scene_confidence: 场景置信度字典（将被更新）
        """
        try:
            # 调整帧大小以提高处理效率
            h, w = frame.shape[:2]
            max_size = self.scene_recognition_config.get('max_frame_size', 512)
            if max(h, w) > max_size:
                scale = max_size / max(h, w)
                new_w, new_h = int(w * scale), int(h * scale)
                frame = cv2.resize(frame, (new_w, new_h))
            
            # 转换为灰度图
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            
            # 计算图像特征
            features = {}
            features['brightness'] = np.mean(gray)
            features['contrast'] = np.std(gray)
            
            # 计算边缘密度
            edges = cv2.Canny(gray, 100, 200)
            features['edge_density'] = np.sum(edges > 0) / (frame.shape[0] * frame.shape[1])
            
            # 计算色彩分布特征
            hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
            features['saturation'] = np.mean(hsv[:, :, 1])
            features['hue_variance'] = np.std(hsv[:, :, 0])
            
            # 缓存特征
            self.scene_features_cache = features
            
            # 交通场景图像特征
            if 60 < features['brightness'] < 200 and features['contrast'] > 40:
                traffic_bonus = min(features['contrast'] / 100, 0.3)
                scene_confidence['traffic'] = min(scene_confidence['traffic'] + traffic_bonus, 0.9)
            
            # 头盔场景图像特征增强
            # 头盔场景通常有特定的特征组合
            # 1. 边缘密度较高（头盔、车辆轮廓）
            # 2. 中等饱和度（户外场景）
            # 3. 一定的对比度
            helmet_feature_score = 0.0
            
            if features['edge_density'] > 0.07:
                helmet_feature_score += 0.15
            if 30 < features['saturation'] < 180:
                helmet_feature_score += 0.1
            if features['contrast'] > 35:
                helmet_feature_score += 0.05
            
            scene_confidence['helmet'] = min(scene_confidence['helmet'] + helmet_feature_score, 0.95)
            
            # 人脸场景图像特征
            if 80 < features['brightness'] < 220 and features['contrast'] > 25 and features['contrast'] < 90:
                face_bonus = min(1.0 - features['edge_density'], 0.3)
                scene_confidence['face'] = min(scene_confidence['face'] + face_bonus, 0.9)
            
            # 全场景模式特征
            if features['hue_variance'] > 70 or features['contrast'] > 80:
                scene_confidence['all'] = min(scene_confidence['all'] + 0.2, 0.8)
                
        except Exception as e:
            self.logger.error(f"图像特征分析失败: {str(e)}")
    
    def _analyze_scene_by_context(self, scene_confidence: Dict[str, float]):
        """
        基于上下文信息分析场景
        
        Args:
            scene_confidence: 场景置信度字典（将被更新）
        """
        current_time = time.time()
        
        # 考虑时间因素
        hour_of_day = time.localtime(current_time).tm_hour
        
        # 夜间场景调整
        if (hour_of_day >= 22) or (hour_of_day < 6):
            # 夜间头盔检测难度增加，降低头盔场景优先级
            scene_confidence['helmet'] = max(0.0, scene_confidence['helmet'] - 0.1)
            # 夜间可能更适合全场景模式
            scene_confidence['all'] = min(scene_confidence['all'] + 0.15, 0.85)
        else:
            # 白天增强头盔场景的识别
            if scene_confidence['helmet'] > 0.3:
                scene_confidence['helmet'] = min(scene_confidence['helmet'] + 0.05, 0.95)
        
        # 考虑场景历史
        recent_switches = sum(1 for h in reversed(self.scene_history) 
                            if current_time - h['timestamp'] < 300)  # 最近5分钟内的切换
        
        if recent_switches > 3:  # 如果场景频繁切换，倾向于全场景模式
            scene_confidence['all'] = min(scene_confidence['all'] + 0.2, 0.9)
        
        # 考虑当前场景的持续时间
        time_in_current = current_time - self.scene_activation_time[self.current_scene]
        if time_in_current > 300:  # 如果在当前场景停留超过5分钟，给予稳定性权重
            scene_confidence[self.current_scene] = min(scene_confidence[self.current_scene] + 0.1, 0.9)
        
        # 归一化置信度
        total_confidence = sum(scene_confidence.values())
        if total_confidence > 0:
            for scene in scene_confidence:
                scene_confidence[scene] = scene_confidence[scene] / total_confidence
    
    def _select_optimal_scene(self, scene_analysis: Dict[str, float]) -> str:
        """
        根据场景分析结果选择最佳场景
        
        Args:
            scene_analysis: 场景分析结果
            
        Returns:
            最佳场景类型
        """
        # 计算综合得分
        scored_scenes = {}
        threshold = self.scene_recognition_config['confidence_threshold']
        current_time = time.time()
        
        for scene, confidence in scene_analysis.items():
            # 1. 基础得分：置信度 × 优先级
            base_score = confidence * self.scene_priority.get(scene, 1)
            
            # 2. 应用场景特定的调整因子
            adjustment = 1.0
            
            # 对于头盔场景的特殊处理
            if scene == 'helmet':
                # 提高头盔场景的优先级，特别是当置信度较高时
                if confidence > 0.6:
                    adjustment = 1.3
                elif confidence > 0.4:
                    adjustment = 1.1
            
            # 3. 考虑场景稳定性因子
            stability_factor = 1.0
            time_in_scene = current_time - self.scene_activation_time[scene]
            
            # 如果场景刚刚被切换过，给予一定的稳定性权重
            if time_in_scene < 60:  # 最近60秒内切换到该场景
                stability_factor = 1.2
            elif time_in_scene > 1800:  # 在场景中停留超过30分钟
                stability_factor = 0.9  # 轻微降低权重，促进场景刷新
            
            # 4. 最终得分
            scored_scenes[scene] = base_score * adjustment * stability_factor
        
        # 找出得分最高的场景
        if scored_scenes:
            best_scene = max(scored_scenes, key=scored_scenes.get)
            best_confidence = scene_analysis[best_scene]
            
            # 优先考虑头盔场景 - 即使置信度略低于阈值但有一定检测可能
            if best_scene == 'helmet' and best_confidence > threshold * 0.8:
                return 'helmet'
            
            # 对于其他场景，只有当置信度超过阈值时才切换
            if best_confidence >= threshold:
                return best_scene
            
            # 如果头盔场景置信度较高但不是最高分，特殊处理
            if scene_analysis.get('helmet', 0) > threshold * 0.9:
                # 如果头盔场景的置信度接近阈值，可以优先选择
                helmet_score = scored_scenes.get('helmet', 0)
                current_best_score = scored_scenes[best_scene]
                if helmet_score > current_best_score * 0.8:
                    return 'helmet'
        
        # 如果没有合适的场景，保持当前场景或选择默认场景
        current_time_in_scene = current_time - self.scene_activation_time[self.current_scene]
        
        # 如果当前场景已经运行较长时间，考虑切换到默认场景
        if current_time_in_scene > 3600:  # 超过1小时
            return 'traffic'
        
        # 否则保持当前场景
        return self.current_scene
    
    def _on_scene_switch(self, old_scene: str, new_scene: str, camera_id: Optional[str]):
        """
        场景切换时的回调函数
        
        Args:
            old_scene: 切换前的场景
            new_scene: 切换后的场景
            camera_id: 摄像头ID
        """
        # 在这里可以添加场景切换时的特殊处理逻辑
        # 例如：加载特定的模型权重，调整处理参数等
        
        self.logger.debug(f"执行场景切换回调: {old_scene} -> {new_scene}")
        
        # 通知相应的引擎进行场景切换准备
        for scene_type, engine in self.detection_engines.items():
            # 检查引擎是否有场景切换方法
            if hasattr(engine, 'on_scene_switch'):
                try:
                    engine.on_scene_switch(old_scene, new_scene, camera_id)
                except Exception as e:
                    self.logger.error(f"引擎 '{scene_type}' 的场景切换回调执行失败: {str(e)}")
    
    def enable_scene(self, scene_type: str):
        """
        启用特定场景
        
        Args:
            scene_type: 场景类型
        """
        if scene_type in self.SUPPORTED_SCENES:
            self.SUPPORTED_SCENES[scene_type]['active'] = True
            self.logger.info(f"启用场景: {scene_type}")
        else:
            self.logger.warning(f"不支持的场景类型: {scene_type}")
    
    def disable_scene(self, scene_type: str):
        """
        禁用特定场景
        
        Args:
            scene_type: 场景类型
        """
        if scene_type in self.SUPPORTED_SCENES:
            # 不允许禁用当前正在使用的场景
            if scene_type == self.current_scene:
                self.logger.error(f"无法禁用当前正在使用的场景: {scene_type}")
                return
            
            self.SUPPORTED_SCENES[scene_type]['active'] = False
            self.logger.info(f"禁用场景: {scene_type}")
        else:
            self.logger.warning(f"不支持的场景类型: {scene_type}")
    
    def get_scene_status(self) -> Dict[str, Any]:
        """
        获取场景管理器的状态信息
        
        Returns:
            状态信息字典
        """
        return {
            'current_scene': self.current_scene,
            'supported_scenes': {k: v['active'] for k, v in self.SUPPORTED_SCENES.items()},
            'scene_counter': self.scene_counter,
            'last_switch_time': self.last_switch_time,
            'auto_switch_enabled': self.scene_recognition_config['enable_auto_switch'],
            'active_time': {
                scene: time.time() - self.scene_activation_time[scene]
                for scene in self.SUPPORTED_SCENES.keys()
            }
        }
    
    def update_recognition_config(self, config_updates: Dict[str, Any]):
        """
        更新场景识别配置
        
        Args:
            config_updates: 要更新的配置项
        """
        self.scene_recognition_config.update(config_updates)
        self.logger.info(f"更新场景识别配置: {config_updates}")
    
    def reset_scene_history(self):
        """
        重置场景切换历史
        """
        self.scene_history.clear()
        self.logger.info("场景切换历史已重置")

# 确保导入cv2
try:
    import cv2
    cv2_available = True
except ImportError:
    cv2_available = False
    logging.warning("OpenCV未安装，场景分析功能将受限")

# 测试代码
if __name__ == "__main__":
    # 配置日志
    logging.basicConfig(level=logging.INFO)
    
    # 创建场景管理器实例
    manager = SceneManager()
    
    print("场景管理器初始化成功")
    print(f"当前场景: {manager.current_scene}")
    print(f"支持的场景: {list(manager.SUPPORTED_SCENES.keys())}")
    
    # 测试场景切换
    manager.switch_scene('helmet')
    print(f"切换后场景: {manager.current_scene}")
    
    # 显示状态信息
    status = manager.get_scene_status()
    print(f"场景状态: {status}")